import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/api/common_service.dart';

import 'package:wanandroid_flutter/model/project_tree_model.dart';
import 'package:wanandroid_flutter/model/project_list_model.dart';
import 'package:wanandroid_flutter/utils/timeline_util.dart';
import 'package:wanandroid_flutter/utils/router_push_util.dart';
import 'package:wanandroid_flutter/components/public_widget.dart';

class ProjectTreePage extends StatefulWidget {
  _ProjectTreePageState createState() => _ProjectTreePageState();
}

class _ProjectTreePageState extends State<ProjectTreePage>
    with TickerProviderStateMixin {
  List<ProjectTreeData> _datas = List();
  TabController _tabController;

  @override
  void initState() {
    _getData();
    super.initState();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _tabController = TabController(length: _datas.length, vsync: this);
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).accentColor,
        title: TabBar(
          controller: _tabController,
          tabs: _datas
              .map((ProjectTreeData item) => Tab(
                    text: item.name,
                  ))
              .toList(),
          indicatorColor: Colors.white,
          isScrollable: true,
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: _datas
            .map((ProjectTreeData item) => NewsList(id: item.id))
            .toList(),
      ),
    );
  }

  Future<Null> _getData() async {
    CommonService().getProjectTree((ProjectTreeModel _projectTreeModel) {
      setState(() {
        _datas = _projectTreeModel.data;
      });
    });
  }
}

class NewsList extends StatefulWidget {
  final int id;
  @override
  NewsList({Key key, this.id}) : super(key: key);

  _NewsListState createState() => _NewsListState();
}

class _NewsListState extends State<NewsList> {
  List<ProjectTreeListDatas> _datas = new List();
  ScrollController _scrollController = ScrollController();
  int _page = 1;
  bool isAllData = false;
  bool noResult = false;

  void initState() {
    _getData();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _getMore();
      }
    });
    super.initState();
  }

  /// ============================================================

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RefreshIndicator(
        onRefresh: _getData,
        child: ListView.separated(
          padding: const EdgeInsets.all(16.0),
          itemBuilder: _renderRow,
          itemCount: _datas.length == 0 ? 1 : _datas.length + 1,
          controller: _scrollController,
          separatorBuilder: (context, int index) {
            return Container(
              height: 0.5,
              color: Colors.black26,
            );
          },
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    if (noResult) return NoResultWidget();

    if (index < _datas.length) {
      return _itemView(context, index);
    }

    if (isAllData) return null;

    return GetMoreWidget();
  }

  Widget _itemView(BuildContext context, int index) {
    return InkWell(
      child: _newsRow(_datas[index]),
      onTap: () {
        RouterPush.toWebview(context, _datas[index].title, _datas[index].link);
      },
    );
  }

  Widget _newsRow(ProjectTreeListDatas item) {
    return Row(
      children: <Widget>[
        Container(
          padding: const EdgeInsets.fromLTRB(8, 16, 8, 8),
          child: Image.network(
            item.envelopePic,
            width: 80,
            height: 120,
            fit: BoxFit.fill,
          ),
        ),
        Expanded(
          child: Column(
            children: <Widget>[
              Container(
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        item.title,
                        style: TextStyle(
                          fontSize: 16.0,
                          fontWeight: FontWeight.bold,
                        ),
                        textAlign: TextAlign.left,
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                padding: const EdgeInsets.fromLTRB(8.0, 0.0, 8.0, 0.0),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        item.desc,
                        style: TextStyle(fontSize: 12.0, color: Colors.grey),
                        textAlign: TextAlign.left,
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                padding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text(
                      item.author,
                      style: TextStyle(
                        fontSize: 12.0,
                        color: Colors.grey,
                      ),
                    ),
                    Expanded(
                      child: Text(
                        TimelineUtil.format(item.publishTime),
                        style: TextStyle(
                          fontSize: 12.0,
                          color: Colors.grey,
                        ),
                        textAlign: TextAlign.right,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// ==============================================================

  Future<Null> _getData() async {
    _page = 1;
    int _id = widget.id;
    // Response response = await dio
    //     .get('http://www.wanandroid.com/project/list/$_page/json?cid=$_id');
    // ProjectTreeListModel projectTreeListModel =
    //     ProjectTreeListModel(response.data);

    // setState(() {
    //   if (projectTreeListModel.data.datas.length == 0) {
    //     noResult = true;
    //   } else if (projectTreeListModel.data.datas.length != 15) {
    //     isAllData = true;
    //   }
    //   _datas = projectTreeListModel.data.datas;
    // });
    CommonService().getProjectList(
        (ProjectTreeListModel _projectTreeListModel) {
      setState(() {
        if (_projectTreeListModel.data.datas.length == 0) {
          noResult = true;
        } else if (_projectTreeListModel.data.datas.length != 15) {
          isAllData = true;
        }
        _datas = _projectTreeListModel.data.datas;
      });
    }, _page, _id);
  }

  Future<Null> _getMore() async {
    _page++;
    int _id = widget.id;

    // Response response = await dio
    //     .get('http://www.wanandroid.com/project/list/$_page/json?cid=$_id');

    // ProjectTreeListModel projectTreeListModel =
    //     ProjectTreeListModel(response.data);
    // setState(() {
    //   if (projectTreeListModel.data.datas.length != 15) {
    //     isAllData = true;
    //   }
    //   _datas.addAll(projectTreeListModel.data.datas);
    // });

    CommonService().getProjectList(
        (ProjectTreeListModel _projectTreeListModel) {
      setState(() {
        if (_projectTreeListModel.data.datas.length != 15) {
          isAllData = true;
        }
        _datas.addAll(_projectTreeListModel.data.datas);
      });
    }, _page, _id);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }
}
